import React, {Component} from 'react'
import {connect} from 'react-redux'
import { List , Button ,Toast} from 'antd-mobile';
const Item = List.Item;
const Brief = Item.Brief;
import {parseQuery} from "../../utils/tools"

class OrderItemBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedPeiyu: this.getItemsAsArray(props.items),
      money:this.props.baseinfo.money || "",
      total:0,
      totalmoney:0
    };
  }
  
  getNumberLabel(item) {
    const {platform} = this.props;
    let parts = item.id.split('-');
    let labelOne = platform['betInfo']['oddinfo'][0][parts[0]];
    return <span className="seperator">{labelOne}</span>
  }

  getNumberContent(item) {
    const {platform} = this.props;
    let parts = item.id.split('-');
    let labelOne = platform['betInfo']['oddinfo'][0][parts[0]];
    let labelTwo = platform['betInfo']['oddinfo'][1][parts[1]];
    let labelThree = platform['betInfo']['odds'][item.id];
    return <div className="bet-content"><span>{labelOne}</span><span>{labelTwo}: </span> <span className="color-red">{item.number}</span></div>
  }

  getItemsAsArray(selectedPeiyu) {
    let itemsArray = [];
    for (var key in selectedPeiyu) {
      itemsArray.push(selectedPeiyu[key]);
    }
    return itemsArray;
  }

  onDeleteItem(item) {
    let selectedPeiyu = this.state.selectedPeiyu.filter((peiyu) => {
      if (peiyu.id == item.id) {
        return false;
      }
      return true;
    });
    var  length = selectedPeiyu.length
    if (length <= 0 ) {
      const {location, history} = this.props;
      let query = parseQuery(location.search);
      let to = `/betcenter/${query.gameCode}`;
      history.push(to);
    } else {
      var total = 0; 
      // console.log(selectedPeiyu,"panghu");
      for(var k in  selectedPeiyu){
        total += +selectedPeiyu[k].money
      }
      if(isNaN(total)){
        total = 0
      }
      // console.log(total,"panghu");
      this.setState({
        selectedPeiyu,
        total:length,
        totalmoney:total
      });
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   this.setState({
  //     selectedPeiyu: this.getItemsAsArray(nextProps.items)
  //   });
  // }

  onSubmit =()=>{
    let items = [];
    let selectedPeiyu = this.state.selectedPeiyu;
    const {location,user} = this.props;
    let query = parseQuery(location.search);
    if(this.state.totalmoney > user.get('info').userMoney){
      return  Toast.fail('下注金额超出您的余额',2);
    }
    for (let peiyu of selectedPeiyu) {
      let saveToItem = {
        uid: peiyu.id,
        rate: peiyu.pl,
        xzje: peiyu.money,
        label: query.gameCode,
        label2: query.pankou
      };
      if (peiyu.number) {
        saveToItem.number = peiyu.number;
      }
      items.push(saveToItem);
      if (!peiyu.money || peiyu.money > peiyu.maxLimit || peiyu.money < peiyu.minLimit ) {
        Toast.fail('下注金额不符合要求',2);
        return ;
      }
    }
    this.props.onSubmit(items);
  }

  onMoneyInput =(item) =>{
    let selectedPeiyu = this.state.selectedPeiyu;
    var total = 0;
    for (let i = 0; i < selectedPeiyu.length; i++) {
      let peiyu = selectedPeiyu[i];
      if (peiyu.id == item.id) {
        if(!isNaN(this.refs[item.id].value)){
          if(this.refs[item.id].value %1 !==0){
            this.refs[item.id].value = ~~this.refs[item.id].value
            return Toast.fail("下注金额必须为整数",1)
          }
        }else{
          return Toast.fail("下注金额必须为整数",1)
        }
          peiyu.money = this.refs[item.id].value;
      }
    }
    for(var k in  this.refs){
      if(k!="totalPrice"){
        total += +this.refs[k].value 
      }
    }
    this.setState({
      totalmoney: total
    });
  }
  componentWillMount(){
    let {money,total,selectedPeiyu} = this.state
    for(var k in selectedPeiyu){
      selectedPeiyu[k].money = money
    }
    this.setState({
      selectedPeiyu,
      total:selectedPeiyu.length,
      totalmoney:selectedPeiyu.length*money,
    })
  }

  componentDidMount(){
    let {money} = this.state
    if(money){
      for(var k in this.refs){
        this.refs[k].value = money
      }
    }
  }
  totalPrice(e){
    let value = e.target.value
    if(!isNaN(value)){
      if(value%1 !==0){
        e.target.value = ~~e.target.value
        return Toast.fail("下注金额必须为整数",1)
      }
      let {selectedPeiyu} = this.state
      for(var k in selectedPeiyu){
        selectedPeiyu[k].money = value
      }
      for(var k in this.refs){
        this.refs[k].value = value
      }
      this.setState({
        selectedPeiyu,
        money:value,
        total:selectedPeiyu.length,
        totalmoney:selectedPeiyu.length*value,
      })
    }
  }

  componentWillReceiveProps(newProps){
    const items = newProps.items;
    const baseinfo = newProps.baseinfo
    let newselect = this.getItemsAsArray(items)
     this.setState({
      selectedPeiyu:newselect,
      total:newselect.length || 0,
      totalmoney:newselect.length*baseinfo.money  || 0,
     })
  }
  render() {
    let items = this.state.selectedPeiyu;
    console.log(items, "base");
    let {money} = this.state
    let _this = this;
    var {name} = this.props.baseinfo
    return (
      <div className="member-bet-items">
         {/* 快捷下注功能 已实现   */}
        <div className="common-money">
          <span>快捷下注金额：</span><input ref="totalPrice" onChange={(e)=>this.totalPrice(e)} type="number" placeholder="输入金额"/>
          </div>
        <div className="inner">
          {items.map((item, index) => {
            return (
              <div key={index} className="item">
                <div  className="orderitem" key={index}>
                <div className="left">
                <input type="number" ref={item.id} onChange={this.onMoneyInput.bind(_this, item)}
                placeholder="输入金额" min={item.minLimit} max={item.maxLimit} value={item.money} />
                </div>
                <h2>{this.getNumberContent(item)}</h2>
                <div className="desc">{name + "-"}{this.getNumberLabel(item)} </div>
                {/* <div className="tips"><span>单注{item.minLimit}-{item.maxLimit}元</span> <span>单期最高{item.maxPeriodLimit}元</span></div> */}
                <div className="close" onClick={this.onDeleteItem.bind(this,item)}>
                <i className="iconfont icon-icon-guanbi"></i>
                </div>
              </div>
              </div> 
            );
          })}
        </div>
        <div className="bottomorder">
                  <List.Item
                  extra={<Button type="warning" size="small" style={{height:"40px",lineHeight:"40px"}} inline onClick={this.onSubmit}>确认投注</Button>}
                >
                  <span className="red">{this.state.total}</span>注
                  共<span className="red">{this.state.totalmoney}</span>元
                  </List.Item>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    betcenter: state.betcenter
  }
}

export default connect(mapStateToProps)(OrderItemBase)